/**
 * 
 */
package de.rotkiv.common.resourcebundle;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import de.rotkiv.common.exception.GeneratorRuntimeException;

/**
 * @author Vik
 *
 */
public class ResourceBundleProvider {


	/** Logger */
	private static final Logger logger = Logger.getLogger(ResourceBundleProvider.class );

	private ResourceBundle bundle;
	private String baseName;
	private boolean isInitialized;


	/**
	 * 
	 * @param baseName
	 */
	public ResourceBundleProvider(String baseName) {
		this.baseName = baseName;
		init();
	}


	private void init() {
		if (isInitialized) {
			logger.info("ResourceBundle already initialized");
			return;
		}

		// Fall 1: Holen des ResourceBundles nur anhand des BaseNamens
		bundle = getBundleIntern(null, baseName);

		// Fall 2: Holen des ResourceBundles mit der Default Locale
		//   -> baseName_<Locale-Country>_<Locale-Language>   z.B. "baseName_de_DE"
		if (bundle == null) {
			Locale locale = Locale.getDefault();
			bundle = getBundleIntern(locale, baseName);
		}

		// Fall 3: Fail-Back - Zugriff mit de_DE:
		if (bundle == null) {
			Locale localeDE = new Locale("de", "DE");
			bundle = getBundleIntern(localeDE, baseName);
		}

		if (bundle == null) {
			throw new GeneratorRuntimeException("Could not get resource bundle, exit.");
		}

		isInitialized = true;
	}


	private static ResourceBundle getBundleIntern(Locale locale, String baseName) {
		ResourceBundle bundle = null;

		try {

			// Logging
			String msg = "try to get resource bundle with base name >" + baseName + "<";
			if (logger.isInfoEnabled() && locale != null) {
				msg += " and Country = " + locale.getCountry() + " and language = " + locale.getLanguage();
			}
			logger.info(msg);


			// Eigentliches Zuweisen mal mit, mal ohne Locale
			if (locale != null) {
				bundle = ResourceBundle.getBundle( baseName, locale );
			} else {
				bundle = ResourceBundle.getBundle( baseName );
			}


			// Logging
			int counter = 0;
			if (bundle != null) {
				counter = bundle.keySet().size();
			}
			logger.info("   ... successfull - bundle size >" + counter + "<");

		} catch ( MissingResourceException e ) {
			logger.info("   ... not successfull - " + e.getLocalizedMessage() );
			// nothing else -> return only null
		}
		return bundle;
	}


	/**
	 * Hole Properties mithilfe des Keys aus dem ResourceBundle
	 * @param key
	 * @return
	 */
	public String getText(String key) {
		String result = key;
		if (bundle != null) {
			result = bundle.getString(key);
		}
		return result;
	}


}
